package com.navi.loaddata.loadService.impl.hisData.cell2;


import com.navi.loaddata.core.mesEntity.MesProducthistory;
import com.navi.loaddata.core.mysqlEntity.EtlConfD;
import com.navi.loaddata.core.repository.impl.MesRepositoryImpl;
import com.navi.loaddata.core.util.ProcessUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional(transactionManager = "secondaryPlatformTransactionManager")
public class LoadHisInfoServiceCELL2 {

    @Autowired
    private MesRepositoryImpl mesdao;

    public Map<String, MesProducthistory> loadHisInInfo(EtlConfD etlConfD, String hisOutKey) {
        Map<String, MesProducthistory> mapHisIn = new HashMap<>();
        List<MesProducthistory> listHisIn = new ArrayList<>();

        StringBuffer hqlIn = new StringBuffer();
        hqlIn.append("FROM MesProducthistory WHERE EVENTNAME='TrackIn'")
                .append("and (PRODUCTNAME,LINKKEY) in(").append(hisOutKey).append(")");
        hqlIn.append(ProcessUtil.getShopMesHql(etlConfD.getShop()))
                .append(ProcessUtil.getOpeMesHql(etlConfD.getOpe()))
                .append(ProcessUtil.getEqptMesHql(etlConfD.getEqpt()));

        listHisIn = mesdao.list(MesProducthistory.class, hqlIn.toString());

        listHisIn.forEach(hisIn -> {
            mapHisIn.put(hisIn.getProductname() + "_" + hisIn.getLinkkey(), hisIn);
        });
        return mapHisIn;
    }

    public List<MesProducthistory> loadHisOutInfo(EtlConfD etlConfD) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        List<MesProducthistory> listHisOut = new ArrayList<>();
        String startTime = sdf.format(etlConfD.getRunStartTimestamp().getTime());
        String endTime = sdf.format(etlConfD.getRunEndTimestamp().getTime());
        StringBuffer hqlOut = new StringBuffer();
        hqlOut.append("FROM MesProducthistory WHERE  EVENTNAME='TrackOut' and OLDPROCESSOPERATIONNAME >'L4100'")
                .append(" and UPDATETIME>=to_date('"+startTime+"','yyyymmddhh24miss')")
                .append(" and UPDATETIME<to_date('"+endTime+"','yyyymmddhh24miss') ");
        hqlOut.append(ProcessUtil.getShopMesHql(etlConfD.getShop()))
                .append(ProcessUtil.getOpeMesHql(etlConfD.getOpe()))
                .append(ProcessUtil.getEqptMesHql(etlConfD.getEqpt()));
        return mesdao.list(MesProducthistory.class, hqlOut.toString());
    }

}
